import {ref, reactive, onMounted} from 'vue'
import {message} from "ant-design-vue";
import {ContactService} from "@/views/erp/system/contact/contactService";
import validate from "ele-admin-pro/packages/validate";


export default function ContactMapSelect(props) {

  const contactSelectObj = {
    flagCollection: reactive({showEdit: false}),

    //新增校验规则
    rules: reactive({
      name: [{
        required: true,
        message: "请输入联系人名称",
        trigger: 'onSubmit'
      }],
      telephone: [
        {
          required: true,
          pattern: validate.phone,
          message: "请输入正确的电话",
          trigger: 'onSubmit'
        }
      ],
      landline: [
        {
          pattern: validate.tel,
          message: "请输入正确的座机号码",
          trigger: 'onSubmit'
        }
      ],
      email: [
        {
          pattern: validate.email,
          message: "请输入正确的邮箱",
          trigger: 'onSubmit'
        }
      ],
      wechat: [
        {
          //微信官方定义的微信号规则
          // 1、可使用6-20个字母、数字、下划线和减号；
          // 2、必须以字母开头（字母不区分大小写）；
          // 3、不支持设置中文。
          pattern: "/^[a-zA-Z][a-zA-Z\\d_-]{5,19}$/",
          message: "请输入正确的微信号",
          trigger: 'onSubmit'
        }
      ],
      jobTitle: [],
      address: [],
    }),
  }
  //当前业务
  const business = reactive({businessId: props.businessId, entityName: props.entity});

  //联系人编辑组件对象
  const contactForm = ref({})

  //联系人新增弹窗对象
  const formForInsert = ref()

  //选择器数据
  const selectObj = ref("手机号(联系人姓名)")

  //选项列表
  const options = ref([])

  //账户信息列表
  const contactList = ref([])
  //账户信息码表,便于选中后展示。
  const contactMap = reactive({});
  //选中的对象
  const contactEntity = ref({label: ''})

  //选中的关键字
  const selectKey = ref(null);

  //新增的实体，用于修改，每次新增之后不会新增一条新数据，
  // 而是在新增的那个选项进行更改。
  // 如果没有新增选项就直接在选址列表中添加该对象。
  const insertEntity = reactive({
    "name": "",
    "entityName": business.entityName,
    "businessId": business.businessId,
    "telephone": "",
    "landline": "",
    "email": "",
    "wechat": "",
    "jobTitle": "",
    "addressId": null,
    "address": null,
    "addressName": "",
  })

  insertEntity.address = {
    addressAbbreviation: "",
    addressType: "",
    businessID: null,
    detailedAddress: "",
    province: "",
    city: "",
    district: "",
    streetAddress: "",
    addressLongitude: 0,
    addressLatitude: 0,
    zipCode: "",
  }


  onMounted(() => {
    reload()
  })


  const reload = () => {
    const conditions = {
      entityName: business.entityName,
      businessId: business.businessId,
      status: "启用"
    }

    const queryParams = {}
    //获取筛选结果（无懒加载）
    queryParams.filters = conditions
    options.value = []
    contactList.value = []

    ContactService.findContacts(queryParams).then((res) => {
      console.log("findContacts", res)
      contactList.value = res.data.datas;
      //打包选项
      packOptions();
    }).catch((error) => {
      message.error(error.message);
    })

  }

  //页面加载时的打包所有选项
  const packOptions = () => {
    let list = contactList.value;
    let optionList = options.value;

    for (let i = 0; i < list.length; i++) {
      list[i].label = list[i].telephone + "(" + list[i].name + ")"
      optionList.push({value: list[i].eid, label: list[i].label})
      contactMap[list[i].eid] = list[i];
    }
  }

  //选项修改事件
  const handleContactChange = (value) => {
    if (contactMap[value]) {
      //选择的时数据库存储实体
      contactEntity.value = contactMap[value]
      selectKey.value = contactMap[value].eid
    } else {
      //初始化
      contactEntity.value = {label: ''}
      selectKey.value = ""
    }
    // console.log(contactEntity)
    // console.log(value)
    reload()
  }

  //新增账户的修改事件
  const editEvent = () => {
    contactSelectObj.flagCollection.showEdit = true
  }

  //用于保存新增的账户结果到选项中。
  const saveOption = () => {
    console.log(insertEntity)
    let list = contactList.value

    //验证唯一性
    console.log("tempList", list)
    for (let i = 0; i < list.length; i++) {
      console.log("contact", list)
      if (list[i].telephone === insertEntity.telephone) {
        message.error("手机号重复，请确认填写是否正确")
        return;
      }
    }
    insertEntity.label = insertEntity.telephone + "(" + insertEntity.name + ")"
    selectObj.value = insertEntity.label
    insertEntity.status = "启用"
    ContactService.saveContact(insertEntity).then((res) => {
      console.log(res);
      selectObj.value = insertEntity.label
      contactEntity.value = insertEntity
      message.success("新增成功")
      cancelFn();
    }).catch((error) => {
      message.error(error.message)
    })

  }

  //取消按钮事件
  const cancelFn = () => {
    contactSelectObj.flagCollection.showEdit = false;
    reload()
  }

  //获取对应选中的数据
  const getOption = () => {
    console.log("value",contactEntity.value)
    return contactEntity.value
  }


  const onSubmit = async () => {
    console.log('submit!',formForInsert);
    const errMap = await formForInsert.value.validate().catch(errMap => errMap)
    if (errMap.errorFields) {
      console.log('error!', errMap);
    } else {
      saveOption()
    }

    // saveOption();
  };

  return {
    formForInsert,
    reload,
    contactSelectObj,
    business,
    cancelFn,
    insertEntity,
    selectObj,
    contactEntity,
    options,
    packOptions,
    handleContactChange,
    editEvent,
    saveOption,
    getOption,
    onSubmit,
    contactForm,
  }

}
